# name : LOCF using lag, template
# key : locf.lag.snippet
# contributor: Shuguang Sun
# --
proc sort data=lab;
  by usubjid lbtestcd avisitn;
run;

data locf;
  length dtype \$15;
  set lab;
  by usubjid lbtestcd avisitn;

  lag1aval = ifn(first.subjid, ., lag(aval));
  lag2aval = ifn(first.subjid, ., lag2(aval));
  lag3aval = ifn(first.subjid, ., lag3(aval));
  lag4aval = ifn(first.subjid, ., lag4(aval));
  avallocf = aval;
  if not first.subjid and missing(aval) then do;
    select (avisit);
      when ("W02") do;
        avallocf = lag1aval;
        if not missing(avallocf) then dtype = 'LOCF';
        end;
      when ("W04") do;
        if lag1aval ne . then avallocf = lag1aval;
        else avallocf = lag2aval;
        if not missing(avallocf) then dtype = 'LOCF';
        end;
      when ("W08") do;
        if lag1aval ne . then avallocf = lag1aval;
        else if lag2aval ne . then avallocf = lag2aval;
        else avallocf = lag3aval;
        if not missing(avallocf) then dtype = 'LOCF';
        end;
      when ("W12") do;
        if lag1aval ne . then avallocf = lag1aval;
        else if lag2aval ne . then avallocf = lag2aval;
        else if lag3aval ne . then avallocf = lag3aval;
        else avallocf = lag4aval;
        if not missing(avallocf) then dtype = 'LOCF';
        end;
      otherwise avallocf = .;
      end;
    end;

run;